"""
金融数据平台API服务主入口
"""
import logging
from fastapi import FastAPI, Depends, HTTPException, status
from fastapi.middleware.cors import CORSMiddleware
from fastapi.security import OAuth2PasswordBearer

from modules.api.routers import stocks, indices, etfs, tasks
from modules.api.auth import get_current_user

# 配置日志
logger = logging.getLogger("api")

# 创建FastAPI应用
app = FastAPI(
    title="金融数据平台API",
    description="提供金融数据查询、管理和监控功能的API服务",
    version="1.0.0",
)

# 添加CORS中间件
app.add_middleware(
    CORSMiddleware,
    allow_origins=["*"],  # 在生产环境中应该限制来源
    allow_credentials=True,
    allow_methods=["*"],
    allow_headers=["*"],
)

# 添加路由
app.include_router(stocks.router, prefix="/api/stocks", tags=["股票数据"])
app.include_router(indices.router, prefix="/api/indices", tags=["指数数据"])
app.include_router(etfs.router, prefix="/api/etfs", tags=["ETF数据"])
app.include_router(tasks.router, prefix="/api/tasks", tags=["任务管理"])


@app.get("/", tags=["健康检查"])
async def root():
    """API服务健康检查"""
    return {
        "status": "ok",
        "message": "金融数据平台API服务运行正常",
        "version": "1.0.0"
    }


@app.get("/api/status", tags=["系统状态"])
async def system_status(current_user = Depends(get_current_user)):
    """获取系统状态信息（需要认证）"""
    try:
        # 这里可以添加更多状态信息，如数据库连接状态、最近任务执行情况等
        return {
            "status": "ok",
            "database": "connected",
            "celery": "running",
            "user": current_user.username,
            "last_update": "2023-01-01 12:00:00"  # 这里应该使用实际的最后更新时间
        }
    except Exception as e:
        logger.error(f"获取系统状态失败: {str(e)}")
        raise HTTPException(
            status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
            detail="获取系统状态时发生错误"
        )